package com.eims.sls_app.ui;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.eims.sls_app.dataaccess.Users;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.MD5;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.MyPushTask;
import com.eims.sls_app.utils.NetWork;
import com.eims.sls_app.view.MyToast;

import org.json.JSONObject;

import bls.juejin.cn.R;

/**
 * Created by lenovo on 2019/11/11.
 */

public class TransferActivity extends MyBaseActivity implements View.OnClickListener {



    private ImageButton ibBack;
    private EditText etUserName,etPassword,etAcount;
    private Button btnSure;
    private String username,pass,acount;

    private String opt, auth, info, time, imei,crc; // 格式化后的参数
    private SharedPreferences settings;
    private ProgressDialog mProgress = null;
    private MyHandler myHandler;
    public static final int SHOW_MSG = 233;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.transfer_layout);
        App.activityS.add(this);
        ibBack= (ImageButton) findViewById(R.id.btn_back);
        etUserName= (EditText) findViewById(R.id.et_userName);
        etPassword= (EditText) findViewById(R.id.et_password);
        etAcount= (EditText) findViewById(R.id.et_acount);
        btnSure= (Button) findViewById(R.id.btn_sure);

        ibBack.setOnClickListener(this);
        btnSure.setOnClickListener(this);
        time = RspBodyBaseBean.getTime();
        imei = RspBodyBaseBean.getIMEI(TransferActivity.this);
        myHandler = new MyHandler();



    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_sure:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                doTransfer();

                break;



        }
    }
    /**
     * 转账
     */
    private void doTransfer() {
        username = etUserName.getText().toString().trim();
        pass = etPassword.getText().toString().trim();
        acount = etAcount.getText().toString().trim();

        if (username.length() == 0) {
            MyToast.getToast(TransferActivity.this, "用户名不能为空").show();
            return;
        }
        if (acount.length() == 0) {
            MyToast.getToast(TransferActivity.this, "金额不能为空").show();
            return;
        }
        if (pass.length() == 0) {
            MyToast.getToast(TransferActivity.this, "密码不能为空").show();
            return;
        }

        if (NetWork.isConnect(TransferActivity.this)) {
            MyAsynTask myAsyn = new MyAsynTask();
            myAsyn.execute();
        } else {
            MyToast.getToast(TransferActivity.this, "网络异常,登陆失败").show();
        }
    }


    /**
     * 异步任务
     */
    class MyAsynTask extends AsyncTask<Void, Integer, String> {
        /**
         * 在后台执行的程序
         */
        @Override
        protected String doInBackground(Void... params) {
            // 对密码进行MD5加密
            pass = MD5.md5(pass + App.MD5_key);
            opt = "116";
            String key = App.key;
            info = RspBodyBaseBean.transferInfo(username, pass,acount);
            crc = RspBodyBaseBean.getCrc(time, imei, key, info,
                    App.user.getUid());
            auth = RspBodyBaseBean.getAuth(crc, time, imei,
                    App.user.getUid());

            String[] values = {opt, auth, info};
            Log.i("login", "登录info---" + info);
            String result = HttpUtils.doPost(App.names, values,
                    App.path);
            Log.e("login", "登录result---" + result);
            if ("-500".equals(result))
                return "-500";

            try {
                JSONObject item = new JSONObject(result);
                if ("false".equals(item.optString("error"))) {



                    return "0";
                } else {
                    // return item.optString("error");
                    return item.optString("msg");
                }
            } catch (Exception ex) {

                return "-110";
            }
        }

        /**
         * 最开始执行的
         */
        @Override
        protected void onPreExecute() {
            mProgress = BaseHelper.showProgress(TransferActivity.this, null,
                    "转账中....", true, true);
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO 这里要传递msg
            try {
                int error = Integer.parseInt(result);
                myHandler.sendEmptyMessage(error);
            } catch (Exception e) {

                MyToast.getToast(TransferActivity.this, result).show();
            }
            // myHandler.sendEmptyMessage(Integer.parseInt(result));
            mProgress.dismiss();
            super.onPostExecute(result);
        }
    }
    /**
     * 处理页面显示的
     */
    @SuppressLint("HandlerLeak")
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            mProgress.dismiss();
            switch (msg.what) {
                case 0:
                    MyToast.getToast(TransferActivity.this, "转账成功").show();
                    Intent intentResuls = getIntent();

                    setResult(1, intentResuls);
                    finish();

                    break;
                case -1:
                    MyToast.getToast(TransferActivity.this, "转账失败").show();
                    break;
                case -110:
                    MyToast.getToast(TransferActivity.this, "转账失败").show();
                    break;
                case -500:
                    MyToast.getToast(TransferActivity.this, "连接超时").show();
                    break;
                case -113:
                    MyToast.getToast(TransferActivity.this, "用户密码错误").show();
                    break;
                case -112:
                    MyToast.getToast(TransferActivity.this, "用户名不存在").show();
                    break;
                case SHOW_MSG:
                    String msgStr = (String) msg.obj;
                    MyToast.getToast(TransferActivity.this, msgStr).show();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    }
}